package cc.shacocloud.mirage.utils.charSequence.finder;


import java.util.Objects;
import java.util.function.Predicate;

/**
 * 字符匹配查找器<br>
 * 查找满足指定{@link Predicate} 匹配的字符所在位置，此类长用于查找某一类字符，如数字等
 */
public class CharMatcherFinder extends TextFinder {
    private static final long serialVersionUID = 1L;
    
    private final Predicate<Character> matcher;
    
    /**
     * 构造
     *
     * @param matcher 被查找的字符匹配器
     */
    public CharMatcherFinder(Predicate<Character> matcher) {
        this.matcher = matcher;
    }
    
    @Override
    public int start(int from) {
        Objects.requireNonNull(this.text);
        final int limit = getValidEndIndex();
        if (negative) {
            for (int i = from; i > limit; i--) {
                if (matcher.test(text.charAt(i))) {
                    return i;
                }
            }
        } else {
            for (int i = from; i < limit; i++) {
                if (matcher.test(text.charAt(i))) {
                    return i;
                }
            }
        }
        return -1;
    }
    
    @Override
    public int end(int start) {
        if (start < 0) {
            return -1;
        }
        return start + 1;
    }
}
